package com.weirdor.elasticsearch.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by weirdor on 2017/12/19.
 *
 * 文件描述：object的一些工具类
 */
public class ObjectUtils {

    public static boolean isBlank(Object object) {
        if (null == object){
            return true;
        }
        else if (object instanceof String){
            return "".equals(object.toString().trim());
        }
        else if (object instanceof Iterable){
            return !((Iterable) object).iterator().hasNext();
        }
        else if (object.getClass().isArray()){
            return Array.getLength(object) == 0;
        }
        else if (object instanceof Map){
            return ((Map) object).size() == 0;
        }
        else if (Number.class.isAssignableFrom(object.getClass())){
            return false;
        }
        else if (Date.class.isAssignableFrom(object.getClass())){
            return false;
        }
        else{
            return false;
        }
    }


    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }


    public static String trimToEmpty(Object str) {
        return (isBlank(str) ? "" : str.toString().trim());
    }


    public static JSONObject isJSONObject(Object args) {
       JSONObject result = null ;

        if(args instanceof JSONObject){
            return (JSONObject)args;
        }

        if(isBlank(args)){
            return result ;
        }
        try {
            return JSON.parseObject(args.toString());
        } catch (Exception e) {
            return result ;
        }
    }
}

